package org.huamoxi.service.impl;

import cn.hutool.core.util.ArrayUtil;
import org.huamoxi.entity.LoginUser;
import org.huamoxi.entity.Role;
import org.huamoxi.entity.User;
import org.huamoxi.service.RoleService;
import org.huamoxi.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * SpringSecurity 用户认证实现类
 */
@Component
public class SecurityUserDetailsImpl implements UserDetailsService {

    // 自己mvc架构中编写的userService
    @Resource
    UserService userService;

    // 自己mvc架构中编写的roleService
    @Resource
    RoleService roleService;

    /**
     * 用户认证
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 设置用户的角色列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Role> roles = roleService.getRolesByUserid(user.getId());
        if (ArrayUtil.isNotEmpty(roles)) {
            roles.forEach(ite -> authorities.add(new SimpleGrantedAuthority("ROLE_" + ite.getId())));
        }

        // oauth2 userDetails的 username 指的是account
        return new LoginUser(user.getId(), user.getAccount(), user.getAccount(), user.getPassword(), authorities);
    }
}
